package com.zyd.service.wechat.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyd.constants.ErrorDef;
import com.zyd.dao.CarLockDao;
import com.zyd.dao.SafeDao;
import com.zyd.dao.SafeOrderDao;
import com.zyd.dao.VehicleDao;
import com.zyd.exception.BusinessException;
import com.zyd.io.model.*;
import com.zyd.io.vo.vehicle.VehicleTrackReqVO;
import com.zyd.io.vo.vehicle.VehicleTrackResVO;
import com.zyd.mappers.*;
import com.zyd.service.login.LoginService;
import com.zyd.service.user.UserService;
import com.zyd.service.vehicle.VehicleService;
import com.zyd.service.wechat.WeChatService;
import com.zyd.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信小程序业务层
 */

@Service
public class WeChatServiceImpl implements WeChatService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatServiceImpl.class);


    private static final long DAY = 86400000L;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserEntityMapper userEntityMapper;

    @Autowired
    private VehicleEntityMapper vehicleEntityMapper;

    @Autowired
    private VehicleService vehicleService;


    @Autowired
    private MealEntityMapper mealEntityMapper;

    @Autowired
    private SafeEntityMapper safeEntityMapper;

    @Autowired
    private VehicleDao vehicleDao;

    @Autowired
    private CarLockDao carLockDao;

    @Autowired
    private SafeOrderDao safeOrderDao;

    @Autowired
    private CountyEntityMapper countyEntityMapper;

    @Autowired
    private SafeDao safeDao;


    @Value("${mch_id}")
    private String mchId;

    @Value("${key}")
    private String key;


    @Value("${weChatAppId}")
    private String appid;

    @Value("${weChatSecret}")
    private String secret;

    @Autowired
    private HttpServletRequest request;

    /**
     * 发送短信
     *
     * @param mobile
     * @throws Exception
     */
    @Override
    public void smsCode(String mobile) throws Exception {

        String code = loginService.getCode(mobile);
        userService.setValidatecode(mobile, code);

    }
    @Override
   public List<Map<String, Object>> findNetwork(){
      String  sql="SELECT * FROM zydzn_network WHERE dr=0 ";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    /**
     * 注册
     *
     * @param param mobile: 手机号, mcode: 验证码, openid: openid
     */
    @Override
    public Map register(Map<String, String> param) {
        String mobile = param.get("mobile");
        if (StringUtils.isEmpty(mobile)) {
            throw new BusinessException("手机号不能为空");
        }
        String mcode = param.get("mcode");
        if (StringUtils.isEmpty(mcode)) {
            throw new BusinessException("验证码不能为空");
        }
        String openid = param.get("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new BusinessException("openid不能为空");
        }
        String validatecode = userService.findValidatecode(mobile);
        if (StringUtils.isEmpty(validatecode)) {
            throw new BusinessException("请先获取验证码");
        }
        String[] split = validatecode.split("&");
        Long codeTime = Long.parseLong(split[1]);
        long nowTime = System.currentTimeMillis();
        if (nowTime - codeTime > 5 * 60 * 60 * 1000) {//过期时间为5分钟
            throw new BusinessException("验证码超时");
        }
        String sysCode = split[0];
        if (!sysCode.equals(mcode)) {//两个验证码不一致
            throw new BusinessException("验证码不正确");

        }
        UserEntityExample example = new UserEntityExample();
        UserEntityExample.Criteria criteria = example.createCriteria();
        example.or(criteria.andMobileEqualTo(mobile).andOpenidEqualTo(openid));
        List<UserEntity> userEntities = userEntityMapper.selectByExample(example);
        if (userEntities != null && userEntities.size() > 0) {
            throw new BusinessException("已被注册");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(mobile);
        userEntity.setOpenid(openid);
        userEntity.setUserclass(1);
        userEntity.setTs(ToolUtils.getNowTime());
        userEntity.setDr(0);
        String id = UUIDUtil.getUUid();
        userEntity.setId(id);
        userEntity.setUsername("wechatUser");
        userEntity.setNickname("微信小程序用户");
        userEntityMapper.insert(userEntity);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user_id", id);
        resultMap.put("userclass", 1);
        resultMap.put("mobile", mobile);
        return resultMap;

    }


    /**
     * 去微信后台获取 openid
     *
     * @param param code
     * @return
     */
    @Override
    public String getOpenIdByWeChat(Map<String, String> param) {

        String code = param.get("code");
        String openid = null;
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("服务器忙");
        }
        HttpClient httpClient = new HttpClient("https://api.weixin.qq.com/sns/jscode2session");
        httpClient.addParameter("appid", appid);
        httpClient.addParameter("secret", secret);
        httpClient.addParameter("js_code", code);
        httpClient.addParameter("grant_type", "authorization_code");
        try {
            httpClient.get();
            String content = httpClient.getContent();
            ObjectMapper mapper = new ObjectMapper();
            Map map = mapper.readValue(content, Map.class);
            openid = (String) map.get("openid");
        } catch (Exception e) {
            LOGGER.info("获取openid失败");
        }
        return openid;
    }

    /**
     * 根据 openid 查询 用户
     *
     * @param openId
     * @return
     */
    @Override
    public UserEntity findUserByOpenId(String openId) {
        UserEntityExample example = new UserEntityExample();
        example.createCriteria().andOpenidEqualTo(openId);
        List<UserEntity> entities = userEntityMapper.selectByExample(example);
        UserEntity userEntity = null;
        try {
            userEntity = entities.get(0);
        } catch (Exception e) {
            LOGGER.info("根据openid:" + openId + "为查询到用户");
        }
        return userEntity;
    }

    /**
     * 根据userid查询车辆
     *
     * @param userid
     * @return
     */
    @Override
    public List<VehicleEntity> findCarByUserid(String userid) {
        VehicleEntityExample example = new VehicleEntityExample();
        UserEntity user = userService.findUser(userid);
        String mobile = "";
        if (user != null) {
            mobile = user.getMobile();
        }
        List<VehicleEntityExample.Criteria> oredCriteria = example.getOredCriteria();
        oredCriteria.add(example.createCriteria().andUseridEqualTo(userid).andDrEqualTo(0));
        oredCriteria.add(example.createCriteria().andMobileEqualTo(mobile).andDrEqualTo(0));
        return vehicleEntityMapper.selectByExample(example);
    }

    /**
     * @param param tagcode :  startTime :   endTime:
     * @return:
     */
    @Override
    public List<VehicleTrackResVO> findCarTrackByExample(Map<String, String> param) throws ParseException {
        String startTime = param.get("startTime");
        String endTime = param.get("endTime");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormatold = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isEmpty(startTime)) {
            startTime = dateFormat.format(new Date(System.currentTimeMillis() - DAY));
        }
        startTime = dateFormat.format(dateFormatold.parse(startTime));
        if (StringUtils.isEmpty(endTime)) {
            endTime = dateFormat.format(new Date(System.currentTimeMillis() + DAY));
        }
        endTime = dateFormat.format(dateFormatold.parse(endTime));
        VehicleTrackReqVO request = new VehicleTrackReqVO();
        request.setTagcode(param.get("tagcode"));
        request.setStartime(startTime);
        request.setEndtime(endTime);
        List<VehicleTrackResVO> vehicleTrack = vehicleService.findVehicleTrack(request);
        return vehicleTrack;
    }

    /**
     * 开锁解锁 0为解锁 1为锁定
     *
     * @param tagcode
     */
    @Override
    @Transactional
    public void updateLock(String tagcode, String state) {

        if ("0".equals(state)) {//如果是解锁
            int islock = vehicleDao.findIslockByTagcode(tagcode);
            if (islock == 0) {
                throw new BusinessException("车辆未被锁");
            }
            vehicleDao.updateLockByTagcode(tagcode, state);
            carLockDao.deletByTagcode(tagcode);
        } else {//如果是加锁
            int islock = vehicleDao.findIslockByTagcode(tagcode);
            if (islock == 1) {
                throw new BusinessException("车辆已被锁");
            }
            List<String> baseidList = vehicleDao.findBaseidByTagidFromSocketNowTOP3(tagcode);
            String baseids = conversionListToString(baseidList);
            vehicleDao.updateLockByTagcode(tagcode, state);
            carLockDao.insert(tagcode, baseids);
        }
    }

    /**
     * 查询对应id的车辆与其保险
     *
     * @param userid
     * @return
     */
    @Override
    public List findMealByuserid(String userid) {
        List<VehicleEntity> carList = findCarByUserid(userid);
        List<Map> maps = carList.stream().map(vehicleEntity -> {
            Map map = new HashMap<>();
            Map res = vehicleDao.findMealByVehicleId(vehicleEntity.getId());
            if (res != null && !res.isEmpty()) {
                map = res;
            }
            map.put("car", vehicleEntity);
            return map;
        }).collect(Collectors.toList());

        return maps;
    }


    /**
     * 根据车辆的区县查询出对应地区的套餐
     *
     * @param area
     * @return
     */
    @Override
    public List findSafeByNewareaid(String area) {
        return safeDao.findSafeByArea(area);
    }


    /**
     * 车辆续保
     *
     * @param param
     * @return
     */
    @Override
    public Map renewal(Map<String, String> param) {
        HashMap result = new HashMap<>();
        String carId = param.get("carId");
        String openid = param.get("openid");
        String safeId = param.get("safeId");
        if (StringUtils.isEmpty(carId) || StringUtils.isEmpty(safeId) || StringUtils.isEmpty(openid)) {
            throw new BusinessException("订单信息不正确,请重试!");
        }

        VehicleEntityExample example = new VehicleEntityExample();
        example.createCriteria().andIdEqualTo(carId).andDrEqualTo(0);
        UserEntityExample userExample = new UserEntityExample();
        userExample.createCriteria().andOpenidEqualTo(openid).andDrEqualTo(0);
        SafeEntityExample safeExample = new SafeEntityExample();
        safeExample.createCriteria().andIdEqualTo(safeId).andDrEqualTo(0);
        VehicleEntity car = null;
        UserEntity user = null;
        SafeEntity safe = null;
        try {
            safe = safeEntityMapper.selectByExample(safeExample).get(0);
            car = vehicleEntityMapper.selectByExample(example).get(0);
            user = userEntityMapper.selectByExample(userExample).get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (car == null || user == null || safe == null) {
            throw new BusinessException("操作失败");
        }
        String orderId = UUIDUtil.getUUid();
        String money = safe.getSalemny().multiply(new BigDecimal(100)).intValue() + "";
        Map map = weChatPay(orderId, openid, money);
        System.out.println(map);
        if ("SUCCESS".equals(map.get("return_code"))) {
            if ("SUCCESS".equals(map.get("result_code"))) {
                //插入数据
                safeOrderDao.inster(orderId, carId, safeId, money);
                /**
                 * 组装前端所需的五个数据跟生成密钥
                 */
                result = creatResult(map);
                result.put("orderId", orderId);
            } else {
                LOGGER.info("调用微信接口异常" + map);
            }
        } else {
            LOGGER.info("调用微信接口异常" + map);
        }
        return result;
    }

    /**
     * 前端如果支付成功 就访问这里 去微信后台查一次 然后修改 订单状态
     *
     * @param orderId
     */
    @Override
    @Transactional
    public Map payInfo(String orderId) {
        Map order = safeOrderDao.findByOrderId(orderId);
        if (order == null || order.isEmpty()) {//未查询系统到订单数据
            throw new BusinessException("支付失败,未查寻到您的订单");
        }
        Map payInfoMap = getWeChatPayInfo(orderId);
        if (payInfoMap == null || payInfoMap.isEmpty()) { //微信系统查询为空
            throw new BusinessException("支付失败,未查寻到您的订单");
        }
        String returnCode = (String) payInfoMap.get("return_code");
        if ("FAIL".equals(returnCode)) { //微信返回的状态码为fail
            LOGGER.info("微信支付结果:失败:" + payInfoMap.get("return_msg"));
            throw new RuntimeException("微信支付结果:失败:" + payInfoMap.get("return_msg"));
        }
        if ("SUCCESS".equals(returnCode)) {//微信返回状态码为成功
            String resultCode = (String) payInfoMap.get("result_code");
            if ("SUCCESS".equals(resultCode)) {//微信 业务结果码 为成功
                String tradeState = (String) payInfoMap.get("trade_state");
                if ("SUCCESS".equals(tradeState)) {//微信交易状态 为支付成功
                    String time_end = (String) payInfoMap.get("time_end");
                    Date timeEnd = formatDate(time_end);
                    safeOrderDao.updateStatusById(1, orderId, timeEnd);
                    /**
                     * 还要去meal表插入一条数据
                     */
                    addMeal(order.get("vehicle_id") + "", order.get("safe_id") + "");
                } else if ("NOTPAY".equals(tradeState) || "USERPAYING".equals(tradeState)) {//未支付,或者支付中 递归再来一次
                    order = payInfo(orderId);
                } else {//如果是其他状态 REFUND—转入退款   CLOSED—已关闭  REVOKED—已撤销（刷卡支付） PAYERROR--支付失败(其他原因，如银行返回失败)
                    safeOrderDao.updateStatusById(2, orderId, new Date());
                }
                LOGGER.info("微信 交易状态描述: " + payInfoMap.get("trade_state_desc"));
            } else {//微信 业务结果码 为fail失败
                String errCodeDes = (String) payInfoMap.get("err_code_des");
                LOGGER.error("微信支付结果:失败:" + errCodeDes);
                throw new RuntimeException("微信支付结果 :失败:" + errCodeDes);
            }
        }
        return order;
    }

    /**
     * 根据车辆id查询明细
     *
     * @param id
     * @return
     */
    @Override
    public VehicleEntity findVehicle(String id) {
        return vehicleService.findVehicle(id);
    }

    /**
     * 查询所有的区县 以供选择
     *
     * @return
     */
    @Override
    public List findCountry() {
        return countyEntityMapper.selectByExample(null);
    }

    /**
     * 将车辆信息存入 审核车辆表中
     *
     * @param vehicle
     */
    @Override
    public UserEntity addVehicleToExamine(VehicleEntity vehicle, Integer state) {
        String s = checkErrorMsg(vehicle);
        if (!StringUtils.isEmpty(s)) {
            throw new BusinessException(s);
        }
        String userid = vehicle.getUserid();
        UserEntityKey userKey = new UserEntityKey();
        userKey.setId(userid);
        UserEntity user = userEntityMapper.selectByPrimaryKey(userKey);
        if (user == null) {
            LOGGER.error("通过userid:" + userid + "未查询到userEntity数据");
            throw new BusinessException("当前用户异常");
        }
        vehicle.setMobile(user.getMobile());
        vehicle.setId(UUIDUtil.getUUid());
        vehicle.setKeeptime(ToolUtils.getNowTime());
        vehicle.setRegtime(ToolUtils.getNowTime());
        vehicle.setCreatetime(ToolUtils.getNowTime());
        SafeEntityKey safeKey = new SafeEntityKey();
        safeKey.setId(vehicle.getMeal_id());
        SafeEntity safe = safeEntityMapper.selectByPrimaryKey(safeKey);
        if (safe == null) {
            LOGGER.error("通过safeId(meal_id):" + vehicle.getMeal_id() + "未查询到套餐数据");
            throw new BusinessException("当前订单状态异常");
        }
        vehicle.setMeal_name(safe.getSalename());
        vehicle.setMeal_money(safe.getSalemny());
        vehicleDao.addVehicleToExamine(vehicle, state);
        return user;
    }

    /**
     * 通过微信支付 添加车辆
     *
     * @param vehicle
     */
    @Override
    public Map addVehicleOfWeChatPay(VehicleEntity vehicle) {
        HashMap result = new HashMap<>();
        //将车辆信息存入 审核车辆表中
        UserEntity user = addVehicleToExamine(vehicle, 2);
        String openid = user.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            LOGGER.error("该用户(" + user.getId() + ":" + user.getUsername() + ")的openid为空");
            throw new BusinessException("用户状态异常");
        }
        String orderId = UUIDUtil.getUUid();
        String money = vehicle.getMeal_money().multiply(new BigDecimal(100)).intValue() + "";
        Map map = weChatPay(orderId, openid, money);
        if ("SUCCESS".equals(map.get("return_code"))) {
            if ("SUCCESS".equals(map.get("result_code"))) {
                //插入数据
                safeOrderDao.inster(orderId, vehicle.getId(), vehicle.getMeal_id(), money);
                /**
                 * 组装前端所需的五个数据跟生成密钥
                 */
                result = creatResult(map);
                result.put("orderId", orderId);
            } else {
                LOGGER.error("调用微信接口异常:" + map);
            }
        }else {
            LOGGER.error("调用微信接口异常:" + map);
        }
        return result;
    }

    /**
     * 添加车辆 微信支付成功后
     *
     * @param orderId
     */
    @Override
    @Transactional
    public void addVehiclePayInfo(String orderId) {
        Map order = payInfo(orderId);
        String vehicleId = (String) order.get("vehicle_id");
        auditPass(vehicleId, 3);
    }

    /**
     * 支付成功
     * 审核通过
     * 抽取出来方便人工审核调用
     *
     * @param vehicleId
     */
    public void auditPass(String vehicleId, Integer state) {
        VehicleEntity vehicle = vehicleDao.findVehicleByIdFromExamine(vehicleId);
        String s = checkErrorMsg(vehicle);
        if (!StringUtils.isEmpty(s)) {
            throw new BusinessException(s);
        }
        vehicleDao.updateExamineVehicleState(vehicleId, state);
        vehicle.setTs(ToolUtils.getNowTime());
        vehicle.setDr(0);
        // 新增创建人
        vehicle.setCreateid("微信用户录入");
        vehicle.setLighttypes(vehicle.getCartype());
        vehicle.setReger("微信录入");
        vehicle.setTheftnum("无");
        vehicleEntityMapper.insertSelective(vehicle);
        if (state == 3) {//微信支付成功状态为3 在payInfo中就走过一次addMeal了
            return;
        }
        addMeal(vehicleId, vehicle.getMeal_id());
    }

    /**
     * 通过userid查询未审核车辆咯
     *
     * @param userid
     * @return
     */
    @Override
    public List<VehicleEntity> findVehicleExamine(String userid) {
        UserEntity user = userService.findUser(userid);
        String mobile = "";
        if (user != null) {
            mobile = user.getMobile();
        }
        return vehicleDao.findVehicleExamineByUseridOrMobile(userid, mobile);
    }

    /**
     * 组装数据 向meal表插入一条数据
     *
     * @param vehicleId
     * @param safeId
     */
    private void addMeal(String vehicleId, String safeId) {
        MealEntity entity = null;
        String endTime = null;
        String startTime = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long now = System.currentTimeMillis();
        SafeEntityExample safeExample = new SafeEntityExample();
        safeExample.createCriteria().andDrEqualTo(0).andIdEqualTo(safeId);
        SafeEntity safe = safeEntityMapper.selectByExample(safeExample).get(0);
        int yearnum = formatYearNum(safe.getYearnum());
        MealEntityExample example = new MealEntityExample();
        example.createCriteria().andVehicle_idEqualTo(vehicleId);
        example.setOrderByClause("end_time DESC");
        try {
            entity = mealEntityMapper.selectByExample(example).get(0);
        } catch (Exception e) {
            LOGGER.error("根据vehicleId:" + vehicleId + "未查询到meal表中的数据");
        }
        if (entity == null || StringUtils.isEmpty(entity.getId())) {
            entity = new MealEntity();
            entity.setVehicle_id(vehicleId);
            Date date = new Date(now);
            startTime = dateFormat.format(date);
            date.setYear(date.getYear() + yearnum);
            endTime = dateFormat.format(date);
        } else {
            String end_time = entity.getEnd_time();
            Date oldEndTime = null;
            try {
                oldEndTime = dateFormat.parse(end_time);
            } catch (ParseException e) {
                LOGGER.error("日期格式转换失败");
            }
            if (oldEndTime.getTime() > now) {
                startTime = end_time;
                oldEndTime.setYear(oldEndTime.getYear() + yearnum);
                endTime = dateFormat.format(oldEndTime);
            } else {
                Date date = new Date(now);
                startTime = dateFormat.format(date);
                date.setYear(date.getYear() + yearnum);
                endTime = dateFormat.format(date);
            }
        }
        entity.setMeal_id(safeId);
        entity.setStart_time(startTime);
        entity.setEnd_time(endTime);
        entity.setMeal_name(safe.getSalename());
        entity.setMeal_money(safe.getSalemny());
        entity.setHas_theftdutp(safe.getHas_theft());
        entity.setHas_thirdduty(safe.getHas_third());
        entity.setHas_accient(safe.getHas_accient());
        entity.setCreate_time(ToolUtils.getNowTime());
        entity.setId(UUIDUtil.getUUid());
        mealEntityMapper.insert(entity);
    }

    /**
     * 将一堆年 转换
     *
     * @param yearnum
     * @return
     */
    private int formatYearNum(String yearnum) {
        String result = "1";
        HashMap<String, String> map = new HashMap<>();
        map.put("一", "1");
        map.put("二", "2");
        map.put("两", "2");
        map.put("三", "3");
        map.put("四", "4");
        map.put("五", "5");
        map.put("六", "6");
        map.put("七", "7");
        map.put("八", "8");
        map.put("九", "9");
        map.put("十", "10");
        if (yearnum.contains("年")) {
            String replace = yearnum.replace("年", "");
            try {
                return Integer.parseInt(replace);
            } catch (NumberFormatException e) {
            }
            String result1 = map.get(replace);
            if (!StringUtils.isEmpty(result1)) {
                result = result1;
            }
        } else {
            try {
                return Integer.parseInt(yearnum);
            } catch (NumberFormatException e) {
            }
        }
        return Integer.parseInt(result);
    }

    /**
     * 格式化微信的时间
     *
     * @param time_end
     * @return
     */
    private Date formatDate(String time_end) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null;
        try {
            date = dateFormat.parse(time_end);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 向微信后台获取订单状态
     *
     * @param orderId
     */
    private Map getWeChatPayInfo(String orderId) {
        Map resultMap = null;
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("mch_id", mchId);//商户号
        String nonceStr = UUIDUtil.getUUid();
        param.put("out_trade_no", orderId);//订单号
        param.put("nonce_str", nonceStr);//随机字符串
        /**
         * 生成签名
         */
        String sign = MD5Utils.MD5Encode(WeChatUtils.formatUrlMap(param, false, false) + "&key=" + key, "UTF-8").toUpperCase();
        param.put("sign", sign);//签名
        String xml = WeChatUtils.mapToXml(param);
        client.setXmlParam(xml);
        try {
            client.post();
            String content = client.getContent();
            resultMap = WeChatUtils.xmlToMap(content);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        System.out.println(resultMap);
        return resultMap;
    }

    /**
     * 构建前端需要的调用接口数据
     *
     * @param map
     * @return
     */
    private HashMap creatResult(Map map) {
        HashMap<String, String> result = new HashMap<>();
        result.put("package", "prepay_id=" + map.get("prepay_id"));
        result.put("nonceStr", map.get("nonce_str") + "");
        result.put("timeStamp", System.currentTimeMillis() / 1000L + "");
        result.put("appId", map.get("appid") + "");
        result.put("signType", "MD5");
        /**
         * 生成签名
         */
        String sign = MD5Utils.MD5Encode(WeChatUtils.formatUrlMap(result, false, false) + "&key=" + key, "UTF-8").toUpperCase();
        result.put("paySign", sign);
        return result;
    }


    /**
     * 把基站编号的list转换为用逗号分隔的字符串
     *
     * @param baseidList
     * @return
     */
    private String conversionListToString(List<String> baseidList) {
        StringBuilder strb = new StringBuilder();
        for (String s : baseidList) {
            strb.append(s).append(",");
        }
        return strb.toString();
    }


    /**
     * 生成订单 调用微信接口
     *
     * @param orderId 订单号
     * @param openid  用户
     * @param money   以分为单位的
     * @return 如果出现了非逻辑上的异常就会出现null
     */
    private Map weChatPay(String orderId, String openid, String money) {
        Map resultMap = null;
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("mch_id", mchId);//商户号
        String nonceStr = UUIDUtil.getUUid();
        param.put("nonce_str", nonceStr);//随机字符串
        param.put("body", "智能防控");//商品描述
        param.put("out_trade_no", orderId);//订单号
        param.put("total_fee", money);//总金额 单位分
        param.put("spbill_create_ip", WeChatUtils.getIpAddress(request));//终端机器ip
        param.put("notify_url", getURl(request) + "/wx/notify");//接收微信支付结果通知的回调地址
        System.out.println(getURl(request));
        param.put("trade_type", "JSAPI");//交易类型
        param.put("openid", openid);
        /**
         * 生成签名
         */
        String sign = MD5Utils.MD5Encode(WeChatUtils.formatUrlMap(param, false, false) + "&key=" + key, "UTF-8").toUpperCase();
        param.put("sign", sign);//签名
        String xml = WeChatUtils.mapToXml(param);
        client.setXmlParam(xml);
        try {
            client.post();
            String content = client.getContent();
            resultMap = WeChatUtils.xmlToMap(content);

        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 获取项目路径 协议+域名+端口+项目路径
     *
     * @param request
     * @return
     */
    private String getURl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    /**
     * 校验
     *
     * @param vehicle
     * @return
     */
    private String checkErrorMsg(VehicleEntity vehicle) {
        String errmsg = null;
        if (StringUtils.isEmpty(vehicle.getCarname())) {
            errmsg = "车主姓名不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(vehicle.getVinno())) {
            errmsg = "车号牌不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(vehicle.getTagcode())) {
            errmsg = "防盗芯片不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(vehicle.getVehiclebrand())) {
            errmsg = "品牌不能为空!";
            return errmsg;
        } else if (StringUtils.isEmpty(vehicle.getCarcolour())) {
            errmsg = "车辆颜色不能为空!";
            return errmsg;
        }
        if (StringUtils.isEmpty(vehicle.getNewareaid())) {
            errmsg = "区县/辖区不能为空!";
            return errmsg;
        } else if (!ValidationUtil.isIdCard(vehicle.getCarid())) {
            errmsg = "身份证号格式不正确";
        }
        VehicleEntityExample entityExample = new VehicleEntityExample();
        entityExample.or().andTagcodeEqualTo(vehicle.getTagcode()).andDrEqualTo(0);
        long count = vehicleEntityMapper.countByExample(entityExample);
        if (count > 0) {
            errmsg = "防盗芯片已存在!";
        }
        return errmsg;
    }

}
